/**
 * 能力管理系统基础框架
 *
 * 本文件定义了能力管理系统的基础框架，包括：
 * - 核心服务接口
 * - 基础组件
 * - 工具函数
 * - 配置管理
 */

import type {
  CapabilityCategory,
  CapabilityComposition,
  CapabilityDefinition,
  CapabilityLifecycle,
  CapabilityPublication,
  CapabilityStatus,
  CapabilitySubscription,
  CapabilityTrade,
  CapabilityType,
  EvaluationResult,
} from '../models/CapabilityDataModels';

// ==================== 核心服务接口 ====================

/**
 * 能力定义服务接口
 */
export interface ICapabilityDefinitionService {
  // 基础CRUD操作
  create(
    definition: Partial<CapabilityDefinition>,
  ): Promise<CapabilityDefinition>;
  update(
    id: string,
    definition: Partial<CapabilityDefinition>,
  ): Promise<CapabilityDefinition>;
  delete(id: string): Promise<boolean>;
  getById(id: string): Promise<CapabilityDefinition>;
  list(params: CapabilityQueryParams): Promise<CapabilityListResult>;

  // 版本管理
  createVersion(id: string, version: string): Promise<CapabilityDefinition>;
  getVersions(id: string): Promise<CapabilityDefinition[]>;
  compareVersions(
    id: string,
    version1: string,
    version2: string,
  ): Promise<VersionComparison>;

  // 状态管理
  changeStatus(id: string, status: CapabilityStatus): Promise<boolean>;
  changeLifecycle(id: string, lifecycle: CapabilityLifecycle): Promise<boolean>;

  // 模板管理
  createTemplate(definition: CapabilityDefinition): Promise<CapabilityTemplate>;
  applyTemplate(
    templateId: string,
    params: Record<string, any>,
  ): Promise<CapabilityDefinition>;

  // 验证和测试
  validate(definition: CapabilityDefinition): Promise<ValidationResult>;
  test(
    definition: CapabilityDefinition,
    testParams: TestParameters,
  ): Promise<TestResult>;
}

/**
 * 能力评估服务接口
 */
export interface ICapabilityEvaluationService {
  // 评估执行
  evaluate(
    capabilityId: string,
    context: EvaluationContext,
  ): Promise<EvaluationResult>;
  batchEvaluate(
    capabilityIds: string[],
    criteria: EvaluationCriteria,
  ): Promise<BatchEvaluationResult>;
  realTimeEvaluate(
    capability: CapabilityDefinition,
    runtimeData: RuntimeData,
  ): Promise<RealTimeEvaluationResult>;

  // 评估管理
  scheduleEvaluation(
    capabilityId: string,
    schedule: EvaluationSchedule,
  ): Promise<string>;
  cancelEvaluation(evaluationId: string): Promise<boolean>;
  getEvaluationHistory(capabilityId: string): Promise<EvaluationResult[]>;

  // 指标管理
  defineMetrics(metrics: EvaluationMetric[]): Promise<boolean>;
  updateMetrics(metrics: EvaluationMetric[]): Promise<boolean>;
  getMetrics(): Promise<EvaluationMetric[]>;

  // 报告生成
  generateReport(evaluationId: string, format: ReportFormat): Promise<Report>;
  exportReport(
    evaluationId: string,
    format: ExportFormat,
  ): Promise<ExportResult>;
}

/**
 * 能力组合服务接口
 */
export interface ICapabilityCompositionService {
  // 组合管理
  createComposition(
    composition: Partial<CapabilityComposition>,
  ): Promise<CapabilityComposition>;
  updateComposition(
    id: string,
    composition: Partial<CapabilityComposition>,
  ): Promise<CapabilityComposition>;
  deleteComposition(id: string): Promise<boolean>;
  getComposition(id: string): Promise<CapabilityComposition>;
  listCompositions(
    params: CompositionQueryParams,
  ): Promise<CompositionListResult>;

  // 组合设计
  designComposition(
    requirements: CompositionRequirements,
  ): Promise<CompositionDesign>;
  validateComposition(
    composition: CapabilityComposition,
  ): Promise<CompositionValidationResult>;
  optimizeComposition(
    composition: CapabilityComposition,
    criteria: OptimizationCriteria,
  ): Promise<CapabilityComposition>;

  // 组合执行
  executeComposition(
    id: string,
    parameters: Record<string, any>,
  ): Promise<CompositionExecutionResult>;
  monitorExecution(executionId: string): Promise<ExecutionStatus>;
  cancelExecution(executionId: string): Promise<boolean>;

  // 组合分析
  analyzeComposition(
    composition: CapabilityComposition,
  ): Promise<CompositionAnalysis>;
  predictPerformance(
    composition: CapabilityComposition,
    load: LoadProfile,
  ): Promise<PerformancePrediction>;
}

/**
 * 能力交易服务接口
 */
export interface ICapabilityTradeService {
  // 发布管理
  publishCapability(
    publication: Partial<CapabilityPublication>,
  ): Promise<CapabilityPublication>;
  updatePublication(
    id: string,
    publication: Partial<CapabilityPublication>,
  ): Promise<CapabilityPublication>;
  unpublishCapability(id: string): Promise<boolean>;
  getPublication(id: string): Promise<CapabilityPublication>;
  listPublications(
    params: PublicationQueryParams,
  ): Promise<PublicationListResult>;

  // 订阅管理
  subscribeCapability(
    subscription: Partial<CapabilitySubscription>,
  ): Promise<CapabilitySubscription>;
  updateSubscription(
    id: string,
    subscription: Partial<CapabilitySubscription>,
  ): Promise<CapabilitySubscription>;
  cancelSubscription(id: string): Promise<boolean>;
  getSubscription(id: string): Promise<CapabilitySubscription>;
  listSubscriptions(
    params: SubscriptionQueryParams,
  ): Promise<SubscriptionListResult>;

  // 交易管理
  createTrade(trade: Partial<CapabilityTrade>): Promise<CapabilityTrade>;
  processTrade(tradeId: string, action: TradeAction): Promise<CapabilityTrade>;
  getTrade(id: string): Promise<CapabilityTrade>;
  listTrades(params: TradeQueryParams): Promise<TradeListResult>;

  // 定价管理
  setPricing(publicationId: string, pricing: PricingModel): Promise<boolean>;
  getPricing(publicationId: string): Promise<PricingModel>;
  calculatePrice(
    publicationId: string,
    usage: UsageData,
  ): Promise<PriceCalculation>;
}

/**
 * 能力监控服务接口
 */
export interface ICapabilityMonitoringService {
  // 监控配置
  configureMonitoring(config: MonitoringConfiguration): Promise<boolean>;
  updateMonitoringConfig(
    id: string,
    config: Partial<MonitoringConfiguration>,
  ): Promise<boolean>;
  getMonitoringConfig(id: string): Promise<MonitoringConfiguration>;

  // 监控数据
  collectMetrics(capabilityId: string): Promise<MonitorMetric[]>;
  getMetrics(
    capabilityId: string,
    timeRange: TimeRange,
  ): Promise<MonitorMetric[]>;
  aggregateMetrics(
    capabilityId: string,
    aggregation: AggregationConfig,
  ): Promise<AggregatedMetrics>;

  // 告警管理
  setAlertRules(capabilityId: string, rules: AlertRule[]): Promise<boolean>;
  getAlertRules(capabilityId: string): Promise<AlertRule[]>;
  triggerAlert(alert: MonitorAlert): Promise<boolean>;
  acknowledgeAlert(alertId: string): Promise<boolean>;
  resolveAlert(alertId: string): Promise<boolean>;

  // 健康检查
  checkHealth(capabilityId: string): Promise<HealthStatus>;
  getHealthHistory(
    capabilityId: string,
    timeRange: TimeRange,
  ): Promise<HealthStatus[]>;
  predictHealth(capabilityId: string): Promise<HealthPrediction>;
}

// ==================== 基础组件 ====================

/**
 * 能力管理器
 */
export class CapabilityManager {
  private compositionService: ICapabilityCompositionService;
  private definitionService: ICapabilityDefinitionService;
  private evaluationService: ICapabilityEvaluationService;
  private monitoringService: ICapabilityMonitoringService;
  private tradeService: ICapabilityTradeService;

  constructor(
    definitionService: ICapabilityDefinitionService,
    evaluationService: ICapabilityEvaluationService,
    compositionService: ICapabilityCompositionService,
    tradeService: ICapabilityTradeService,
    monitoringService: ICapabilityMonitoringService,
  ) {
    this.definitionService = definitionService;
    this.evaluationService = evaluationService;
    this.compositionService = compositionService;
    this.tradeService = tradeService;
    this.monitoringService = monitoringService;
  }

  /**
   * 获取能力组合服务
   */
  getCompositionService(): ICapabilityCompositionService {
    return this.compositionService;
  }

  /**
   * 获取能力定义服务
   */
  getDefinitionService(): ICapabilityDefinitionService {
    return this.definitionService;
  }

  /**
   * 获取能力评估服务
   */
  getEvaluationService(): ICapabilityEvaluationService {
    return this.evaluationService;
  }

  /**
   * 获取能力监控服务
   */
  getMonitoringService(): ICapabilityMonitoringService {
    return this.monitoringService;
  }

  /**
   * 获取能力交易服务
   */
  getTradeService(): ICapabilityTradeService {
    return this.tradeService;
  }

  /**
   * 完整的能力生命周期管理
   */
  async manageCapabilityLifecycle(
    capabilityId: string,
    action: LifecycleAction,
  ): Promise<boolean> {
    try {
      switch (action) {
        case 'create': {
          // 创建能力
          break;
        }
        case 'evaluate': {
          // 评估能力
          await this.evaluationService.evaluate(capabilityId, {});
          break;
        }
        case 'monitor': {
          // 监控能力
          await this.monitoringService.configureMonitoring({ enabled: true });
          break;
        }
        case 'publish': {
          // 发布能力
          break;
        }
        case 'retire': {
          // 退役能力
          break;
        }
        default: {
          throw new Error(`Unknown lifecycle action: ${action}`);
        }
      }
      return true;
    } catch (error) {
      console.error('Capability lifecycle management failed:', error);
      return false;
    }
  }
}

/**
 * 能力注册器
 */
export class CapabilityRegistry {
  private capabilities: Map<string, CapabilityDefinition> = new Map();
  private categories: Map<string, CapabilityCategory> = new Map();
  private types: Map<string, CapabilityType> = new Map();

  /**
   * 查找能力
   */
  find(criteria: CapabilitySearchCriteria): CapabilityDefinition[] {
    const results: CapabilityDefinition[] = [];

    for (const capability of this.capabilities.values()) {
      if (this.matchesCriteria(capability, criteria)) {
        results.push(capability);
      }
    }

    return results;
  }

  /**
   * 获取所有能力
   */
  getAll(): CapabilityDefinition[] {
    return [...this.capabilities.values()];
  }

  /**
   * 获取能力分类
   */
  getCategories(): CapabilityCategory[] {
    return [...this.categories.values()];
  }

  /**
   * 获取能力类型
   */
  getTypes(): CapabilityType[] {
    return [...this.types.values()];
  }

  /**
   * 注册能力
   */
  register(capability: CapabilityDefinition): boolean {
    try {
      this.capabilities.set(capability.id, capability);
      this.categories.set(capability.category, capability.category);
      this.types.set(capability.type, capability.type);
      return true;
    } catch (error) {
      console.error('Failed to register capability:', error);
      return false;
    }
  }

  /**
   * 注销能力
   */
  unregister(capabilityId: string): boolean {
    try {
      return this.capabilities.delete(capabilityId);
    } catch (error) {
      console.error('Failed to unregister capability:', error);
      return false;
    }
  }

  private matchesCriteria(
    capability: CapabilityDefinition,
    criteria: CapabilitySearchCriteria,
  ): boolean {
    if (criteria.category && capability.category !== criteria.category) {
      return false;
    }
    if (criteria.type && capability.type !== criteria.type) {
      return false;
    }
    if (criteria.status && capability.status !== criteria.status) {
      return false;
    }
    if (
      criteria.tags &&
      !criteria.tags.every((tag) => capability.tags.includes(tag))
    ) {
      return false;
    }
    if (
      criteria.keyword &&
      !capability.name.toLowerCase().includes(criteria.keyword.toLowerCase())
    ) {
      return false;
    }
    return true;
  }
}

/**
 * 能力验证器
 */
export class CapabilityValidator {
  /**
   * 验证能力定义
   */
  validateDefinition(definition: CapabilityDefinition): ValidationResult {
    const errors: ValidationError[] = [];
    const warnings: ValidationWarning[] = [];

    // 基本信息验证
    if (!definition.name || definition.name.trim().length === 0) {
      errors.push({ field: 'name', message: '能力名称不能为空' });
    }

    if (!definition.code || definition.code.trim().length === 0) {
      errors.push({ field: 'code', message: '能力代码不能为空' });
    }

    if (!definition.description || definition.description.trim().length === 0) {
      warnings.push({ field: 'description', message: '建议提供能力描述' });
    }

    // 规格验证
    if (definition.specification) {
      const specValidation = this.validateSpecification(
        definition.specification,
      );
      errors.push(...specValidation.errors);
      warnings.push(...specValidation.warnings);
    }

    // 接口验证
    if (definition.interfaces && definition.interfaces.length > 0) {
      const interfaceValidation = this.validateInterfaces(
        definition.interfaces,
      );
      errors.push(...interfaceValidation.errors);
      warnings.push(...interfaceValidation.warnings);
    }

    // 约束验证
    if (definition.constraints && definition.constraints.length > 0) {
      const constraintValidation = this.validateConstraints(
        definition.constraints,
      );
      errors.push(...constraintValidation.errors);
      warnings.push(...constraintValidation.warnings);
    }

    return {
      isValid: errors.length === 0,
      errors,
      warnings,
    };
  }

  /**
   * 验证约束条件
   */
  private validateConstraints(constraints: any[]): ValidationResult {
    const errors: ValidationError[] = [];
    const warnings: ValidationWarning[] = [];

    for (const constraint of constraints) {
      if (!constraint.name || constraint.name.trim().length === 0) {
        errors.push({ field: 'constraint.name', message: '约束名称不能为空' });
      }

      if (!constraint.expression || constraint.expression.trim().length === 0) {
        errors.push({
          field: 'constraint.expression',
          message: '约束表达式不能为空',
        });
      }
    }

    return { isValid: errors.length === 0, errors, warnings };
  }

  /**
   * 验证接口定义
   */
  private validateInterfaces(interfaces: any[]): ValidationResult {
    const errors: ValidationError[] = [];
    const warnings: ValidationWarning[] = [];

    for (const iface of interfaces) {
      if (!iface.name || iface.name.trim().length === 0) {
        errors.push({ field: 'interface.name', message: '接口名称不能为空' });
      }

      if (!iface.method || iface.method.trim().length === 0) {
        errors.push({ field: 'interface.method', message: '接口方法不能为空' });
      }

      if (!iface.path || iface.path.trim().length === 0) {
        errors.push({ field: 'interface.path', message: '接口路径不能为空' });
      }
    }

    return { isValid: errors.length === 0, errors, warnings };
  }

  /**
   * 验证能力规格
   */
  private validateSpecification(specification: any): ValidationResult {
    const errors: ValidationError[] = [];
    const warnings: ValidationWarning[] = [];

    // 输入输出验证
    if (specification.inputs && !Array.isArray(specification.inputs)) {
      errors.push({
        field: 'specification.inputs',
        message: '输入规格必须是数组',
      });
    }

    if (specification.outputs && !Array.isArray(specification.outputs)) {
      errors.push({
        field: 'specification.outputs',
        message: '输出规格必须是数组',
      });
    }

    return { isValid: errors.length === 0, errors, warnings };
  }
}

// ==================== 工具函数 ====================

/**
 * 能力工具类
 */
export const CapabilityUtils = {
  /**
   * 生成能力ID
   */
  generateId(prefix: string = 'cap'): string {
    const timestamp = Date.now().toString(36);
    const random = Math.random().toString(36).slice(2, 7);
    return `${prefix}_${timestamp}_${random}`;
  },

  /**
   * 生成版本号
   */
  generateVersion(
    major: number = 1,
    minor: number = 0,
    patch: number = 0,
  ): string {
    return `${major}.${minor}.${patch}`;
  },

  /**
   * 计算能力评分
   */
  calculateScore(
    scores: Record<string, number>,
    weights: Record<string, number> = {},
  ): number {
    const defaultWeights = {
      functional: 0.25,
      performance: 0.2,
      security: 0.2,
      availability: 0.15,
      compatibility: 0.1,
      business: 0.1,
    };

    const finalWeights = { ...defaultWeights, ...weights };
    let totalScore = 0;
    let totalWeight = 0;

    for (const [category, score] of Object.entries(scores)) {
      const weight = finalWeights[category] || 0;
      totalScore += score * weight;
      totalWeight += weight;
    }

    return totalWeight > 0 ? totalScore / totalWeight : 0;
  },

  /**
   * 格式化能力信息
   */
  formatCapabilityInfo(capability: CapabilityDefinition): string {
    return `${capability.name} (${capability.code}) v${capability.version}`;
  },

  /**
   * 解析能力标签
   */
  parseTags(tagString: string): string[] {
    return tagString
      .split(',')
      .map((tag) => tag.trim())
      .filter((tag) => tag.length > 0);
  },

  /**
   * 合并能力标签
   */
  mergeTags(tags1: string[], tags2: string[]): string[] {
    const merged = new Set([...tags1, ...tags2]);
    return [...merged].sort();
  },

  /**
   * 验证能力代码格式
   */
  validateCode(code: string): boolean {
    const codePattern = /^[a-z][\w-]*$/i;
    return codePattern.test(code);
  },

  /**
   * 验证版本号格式
   */
  validateVersion(version: string): boolean {
    const versionPattern = /^\d+\.\d+\.\d+$/;
    return versionPattern.test(version);
  },

  /**
   * 比较版本号
   */
  compareVersions(version1: string, version2: string): number {
    const v1 = version1.split('.').map(Number);
    const v2 = version2.split('.').map(Number);

    for (let i = 0; i < Math.max(v1.length, v2.length); i++) {
      const num1 = v1[i] || 0;
      const num2 = v2[i] || 0;

      if (num1 > num2) return 1;
      if (num1 < num2) return -1;
    }

    return 0;
  },
};

/**
 * 能力配置管理器
 */
export class CapabilityConfigManager {
  private config: CapabilitySystemConfig;

  constructor(config: CapabilitySystemConfig) {
    this.config = config;
  }

  /**
   * 获取配置
   */
  getConfig(): CapabilitySystemConfig {
    return this.config;
  }

  /**
   * 获取评估配置
   */
  getEvaluationConfig(): EvaluationConfig {
    return this.config.evaluation;
  }

  /**
   * 获取监控配置
   */
  getMonitoringConfig(): MonitoringConfig {
    return this.config.monitoring;
  }

  /**
   * 获取交易配置
   */
  getTradeConfig(): TradeConfig {
    return this.config.trade;
  }

  /**
   * 更新配置
   */
  updateConfig(updates: Partial<CapabilitySystemConfig>): void {
    this.config = { ...this.config, ...updates };
  }
}

// ==================== 类型定义 ====================

/**
 * 能力查询参数
 */
export interface CapabilityQueryParams {
  category?: CapabilityCategory;
  type?: CapabilityType;
  status?: CapabilityStatus;
  tags?: string[];
  keyword?: string;
  page?: number;
  pageSize?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * 能力查询结果
 */
export interface CapabilityListResult {
  items: CapabilityDefinition[];
  total: number;
  page: number;
  pageSize: number;
  totalPages: number;
}

/**
 * 版本比较结果
 */
export interface VersionComparison {
  version1: CapabilityDefinition;
  version2: CapabilityDefinition;
  differences: VersionDifference[];
  summary: VersionComparisonSummary;
}

/**
 * 版本差异
 */
export interface VersionDifference {
  field: string;
  oldValue: any;
  newValue: any;
  type: 'added' | 'modified' | 'removed';
}

/**
 * 版本比较摘要
 */
export interface VersionComparisonSummary {
  totalChanges: number;
  breakingChanges: number;
  newFeatures: number;
  bugFixes: number;
}

/**
 * 验证结果
 */
export interface ValidationResult {
  isValid: boolean;
  errors: ValidationError[];
  warnings: ValidationWarning[];
}

/**
 * 验证错误
 */
export interface ValidationError {
  field: string;
  message: string;
  code?: string;
}

/**
 * 验证警告
 */
export interface ValidationWarning {
  field: string;
  message: string;
  code?: string;
}

/**
 * 测试参数
 */
export interface TestParameters {
  inputs: Record<string, any>;
  expectedOutputs: Record<string, any>;
  timeout?: number;
  retries?: number;
}

/**
 * 测试结果
 */
export interface TestResult {
  success: boolean;
  actualOutputs: Record<string, any>;
  executionTime: number;
  errors: string[];
  warnings: string[];
}

/**
 * 评估上下文
 */
export interface EvaluationContext {
  environment: string;
  loadLevel: 'high' | 'low' | 'medium';
  timeRange: string;
  evaluator: string;
  criteria: EvaluationCriteria;
}

/**
 * 评估标准
 */
export interface EvaluationCriteria {
  functional: boolean;
  performance: boolean;
  security: boolean;
  availability: boolean;
  compatibility: boolean;
  business: boolean;
  weights?: Record<string, number>;
}

/**
 * 批量评估结果
 */
export interface BatchEvaluationResult {
  results: EvaluationResult[];
  summary: BatchEvaluationSummary;
  errors: string[];
}

/**
 * 批量评估摘要
 */
export interface BatchEvaluationSummary {
  total: number;
  successful: number;
  failed: number;
  averageScore: number;
  bestScore: number;
  worstScore: number;
}

/**
 * 实时评估结果
 */
export interface RealTimeEvaluationResult {
  capabilityId: string;
  timestamp: string;
  score: number;
  metrics: Record<string, number>;
  status: 'critical' | 'healthy' | 'warning';
}

/**
 * 评估调度
 */
export interface EvaluationSchedule {
  frequency: 'daily' | 'monthly' | 'once' | 'weekly';
  startTime: string;
  endTime?: string;
  timezone: string;
  enabled: boolean;
}

/**
 * 评估指标
 */
export interface EvaluationMetric {
  id: string;
  name: string;
  type: string;
  description: string;
  unit: string;
  weight: number;
  thresholds: MetricThreshold[];
}

/**
 * 指标阈值
 */
export interface MetricThreshold {
  level: 'critical' | 'warning';
  value: number;
  operator: 'eq' | 'gt' | 'gte' | 'lt' | 'lte';
}

/**
 * 报告格式
 */
export type ReportFormat = 'html' | 'json' | 'pdf' | 'xml';

/**
 * 导出格式
 */
export type ExportFormat = 'csv' | 'excel' | 'json' | 'xml';

/**
 * 报告
 */
export interface Report {
  id: string;
  title: string;
  content: string;
  format: ReportFormat;
  generatedAt: string;
  size: number;
}

/**
 * 导出结果
 */
export interface ExportResult {
  success: boolean;
  fileUrl?: string;
  fileName?: string;
  fileSize?: number;
  error?: string;
}

/**
 * 组合查询参数
 */
export interface CompositionQueryParams {
  status?: string;
  category?: string;
  creator?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 组合查询结果
 */
export interface CompositionListResult {
  items: CapabilityComposition[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 组合需求
 */
export interface CompositionRequirements {
  functional: string[];
  performance: PerformanceRequirement;
  security: SecurityRequirement;
  budget: number;
  timeline: string;
}

/**
 * 组合设计
 */
export interface CompositionDesign {
  composition: CapabilityComposition;
  alternatives: CapabilityComposition[];
  recommendations: string[];
  estimatedCost: number;
  estimatedTime: string;
}

/**
 * 组合验证结果
 */
export interface CompositionValidationResult {
  isValid: boolean;
  errors: string[];
  warnings: string[];
  dependencies: string[];
  conflicts: string[];
}

/**
 * 优化标准
 */
export interface OptimizationCriteria {
  performance: boolean;
  cost: boolean;
  reliability: boolean;
  security: boolean;
  weights: Record<string, number>;
}

/**
 * 组合执行结果
 */
export interface CompositionExecutionResult {
  executionId: string;
  status: 'cancelled' | 'completed' | 'failed' | 'running';
  startTime: string;
  endTime?: string;
  results: Record<string, any>;
  errors: string[];
  logs: string[];
}

/**
 * 执行状态
 */
export interface ExecutionStatus {
  executionId: string;
  status: 'cancelled' | 'completed' | 'failed' | 'running';
  progress: number;
  currentStep: string;
  estimatedTimeRemaining: string;
  results: Record<string, any>;
}

/**
 * 组合分析
 */
export interface CompositionAnalysis {
  complexity: number;
  performance: PerformanceAnalysis;
  reliability: ReliabilityAnalysis;
  security: SecurityAnalysis;
  cost: CostAnalysis;
}

/**
 * 性能分析
 */
export interface PerformanceAnalysis {
  responseTime: number;
  throughput: number;
  resourceUsage: Record<string, number>;
  bottlenecks: string[];
}

/**
 * 可靠性分析
 */
export interface ReliabilityAnalysis {
  availability: number;
  failureRate: number;
  mttf: number;
  mttr: number;
  weakPoints: string[];
}

/**
 * 安全分析
 */
export interface SecurityAnalysis {
  riskLevel: 'high' | 'low' | 'medium';
  vulnerabilities: string[];
  compliance: Record<string, boolean>;
  recommendations: string[];
}

/**
 * 成本分析
 */
export interface CostAnalysis {
  totalCost: number;
  breakdown: Record<string, number>;
  optimization: CostOptimization[];
}

/**
 * 成本优化
 */
export interface CostOptimization {
  area: string;
  currentCost: number;
  optimizedCost: number;
  savings: number;
  actions: string[];
}

/**
 * 性能预测
 */
export interface PerformancePrediction {
  responseTime: number;
  throughput: number;
  resourceUsage: Record<string, number>;
  confidence: number;
  assumptions: string[];
}

/**
 * 负载配置
 */
export interface LoadProfile {
  concurrentUsers: number;
  requestRate: number;
  dataVolume: number;
  peakLoad: number;
}

/**
 * 发布查询参数
 */
export interface PublicationQueryParams {
  category?: string;
  status?: string;
  publisher?: string;
  priceRange?: PriceRange;
  page?: number;
  pageSize?: number;
}

/**
 * 发布查询结果
 */
export interface PublicationListResult {
  items: CapabilityPublication[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 订阅查询参数
 */
export interface SubscriptionQueryParams {
  status?: string;
  subscriber?: string;
  publicationId?: string;
  page?: number;
  pageSize?: number;
}

/**
 * 订阅查询结果
 */
export interface SubscriptionListResult {
  items: CapabilitySubscription[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 交易查询参数
 */
export interface TradeQueryParams {
  status?: string;
  buyer?: string;
  seller?: string;
  dateRange?: DateRange;
  page?: number;
  pageSize?: number;
}

/**
 * 交易查询结果
 */
export interface TradeListResult {
  items: CapabilityTrade[];
  total: number;
  page: number;
  pageSize: number;
}

/**
 * 交易动作
 */
export type TradeAction = 'approve' | 'cancel' | 'complete' | 'reject';

/**
 * 价格范围
 */
export interface PriceRange {
  min: number;
  max: number;
  currency: string;
}

/**
 * 日期范围
 */
export interface DateRange {
  start: string;
  end: string;
}

/**
 * 使用数据
 */
export interface UsageData {
  quantity: number;
  duration: number;
  features: string[];
  customParams: Record<string, any>;
}

/**
 * 价格计算
 */
export interface PriceCalculation {
  basePrice: number;
  usagePrice: number;
  discount: number;
  totalPrice: number;
  currency: string;
  breakdown: Record<string, number>;
}

/**
 * 监控配置
 */
export interface MonitoringConfiguration {
  enabled: boolean;
  interval: number;
  metrics: string[];
  thresholds: Record<string, number>;
  alerts: AlertConfig[];
}

/**
 * 告警配置
 */
export interface AlertConfig {
  metric: string;
  condition: string;
  threshold: number;
  severity: string;
  actions: string[];
}

/**
 * 时间范围
 */
export interface TimeRange {
  start: string;
  end: string;
}

/**
 * 聚合配置
 */
export interface AggregationConfig {
  function: 'avg' | 'count' | 'max' | 'min' | 'sum';
  interval: string;
  groupBy: string[];
}

/**
 * 聚合指标
 */
export interface AggregatedMetrics {
  timestamp: string;
  metrics: Record<string, number>;
  count: number;
}

/**
 * 告警规则
 */
export interface AlertRule {
  id: string;
  name: string;
  metric: string;
  condition: string;
  threshold: number;
  severity: string;
  enabled: boolean;
}

/**
 * 健康状态
 */
export interface HealthStatus {
  status: 'critical' | 'healthy' | 'unknown' | 'warning';
  score: number;
  issues: string[];
  lastCheck: string;
  nextCheck: string;
}

/**
 * 健康预测
 */
export interface HealthPrediction {
  predictedStatus: string;
  confidence: number;
  factors: string[];
  recommendations: string[];
}

/**
 * 能力搜索条件
 */
export interface CapabilitySearchCriteria {
  category?: CapabilityCategory;
  type?: CapabilityType;
  status?: CapabilityStatus;
  tags?: string[];
  keyword?: string;
}

/**
 * 生命周期动作
 */
export type LifecycleAction =
  | 'create'
  | 'evaluate'
  | 'monitor'
  | 'publish'
  | 'retire';

/**
 * 运行时数据
 */
export interface RuntimeData {
  timestamp: string;
  metrics: Record<string, number>;
  events: string[];
  context: Record<string, any>;
}

/**
 * 能力模板
 */
export interface CapabilityTemplate {
  id: string;
  name: string;
  description: string;
  template: CapabilityDefinition;
  parameters: TemplateParameter[];
  usage: number;
  rating: number;
}

/**
 * 模板参数
 */
export interface TemplateParameter {
  name: string;
  type: string;
  description: string;
  required: boolean;
  defaultValue?: any;
  validation?: string;
}

/**
 * 能力系统配置
 */
export interface CapabilitySystemConfig {
  evaluation: EvaluationConfig;
  monitoring: MonitoringConfig;
  trade: TradeConfig;
  security: SecurityConfig;
  performance: PerformanceConfig;
}

/**
 * 评估配置
 */
export interface EvaluationConfig {
  autoEvaluation: boolean;
  evaluationInterval: number;
  defaultWeights: Record<string, number>;
  thresholds: Record<string, number>;
}

/**
 * 监控配置
 */
export interface MonitoringConfig {
  enabled: boolean;
  collectionInterval: number;
  retentionPeriod: number;
  alertChannels: string[];
}

/**
 * 交易配置
 */
export interface TradeConfig {
  enabled: boolean;
  approvalRequired: boolean;
  defaultCurrency: string;
  commissionRate: number;
}

/**
 * 安全配置
 */
export interface SecurityConfig {
  encryptionEnabled: boolean;
  authenticationRequired: boolean;
  auditLogging: boolean;
  accessControl: string;
}

/**
 * 性能配置
 */
export interface PerformanceConfig {
  cacheEnabled: boolean;
  cacheSize: number;
  cacheTtl: number;
  maxConcurrency: number;
}

export default {
  CapabilityManager,
  CapabilityRegistry,
  CapabilityValidator,
  CapabilityUtils,
  CapabilityConfigManager,
};
